package com.wsd.smartcarwasher.configuration;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;
import com.wsd.smartcarwasher.constans.ResultState;
import com.wsd.smartcarwasher.util.ReturnUtil;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyExceptionHandler implements HandlerExceptionResolver {
    private Logger logger = LoggerFactory.getLogger(MyExceptionHandler.class);

    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) {
        ModelAndView mv = new ModelAndView();
        FastJsonJsonView view = new FastJsonJsonView();
        if (ex instanceof UnauthenticatedException) {
            view.setAttributesMap(ReturnUtil.Error(ResultState.UNAUTHENTICATION_ERROR.getMsg()));
        } else if (ex instanceof UnauthorizedException) {
            view.setAttributesMap(ReturnUtil.Error(ResultState.NO_PERMISSION.getMsg()));
        } else if (ex instanceof LockedAccountException){
            view.setAttributesMap(ReturnUtil.Error(ResultState.LOGIN_STATUS_EXPIRED.getMsg()));
        }else {
            view.setAttributesMap(ReturnUtil.Error(ResultState.UNEXPECTED_ERROR.getMsg()));
            logger.error("error:", ex);
        }
        mv.setView(view);
        return mv;
    }
}
